'''
Created on 19/04/2012

@author: glenn
'''

import os
import subprocess
import gettext
import cherrypy
#from cherrypy.lib.static import serve_file # dependency

from audio_converter import AudioConfig

__version__ = subprocess.check_output(["hg", "id", "-i"])

lang = "en"

gettext.bindtextdomain('slidespeech', os.path.join(os.getcwd(), 'locale'))
gettext.textdomain('slidespeech')
_ = gettext.gettext

def uploadPresentationFile(version, language, errorMessage):
    """Display the 'Upload presentation file' form."""
    from jinja2 import Environment, FileSystemLoader
    env = Environment(loader=FileSystemLoader('templates'), extensions=['jinja2.ext.i18n'])    
    domain = 'slidespeech'
    try:
        trans = gettext.translation(domain, os.path.join(os.getcwd(), 'locale'), [language])
    except IOError:
        # This probably means that there is no .mo file.
        # FIXME: This needs to be generated during installation
        trans = gettext.NullTranslations()

    env.install_gettext_translations(trans)
    template = env.get_template('uploadPresentationFile.html')
    return template.render(LANGUAGE=language, errorMessage=errorMessage,
                           version=version,
                           ttsURL=AudioConfig.ttsURL, ttsEngine=AudioConfig.ttsEngine)



class UploadPage():
    def index(self):
        # FIXME: where do we get the user's language preference from?
        return uploadPresentationFile(__version__, lang, None)
    
    index.exposed = True
    
    def uploadODP(self, myFile=None, email=None, title=None, author=None):
        if email==None or 0==len(email.strip()):
            return uploadPresentationFile(__version__, lang, _("Please supply your e-mail address."))
        if -1==email.find('@'):
            return uploadPresentationFile(__version__, lang, _("Please supply a valid e-mail address."))
        if myFile is None:
            return uploadPresentationFile(__version__, lang, _("Please supply an Open Document Presentation (.odp) file."))
        (sourcepath, ODPFile) = os.path.split(myFile.filename)
        (ODPFileStem, ODPFileExtension) = os.path.splitext(ODPFile)
        if not (ODPFileExtension in (".ODP",".odp")):
            return uploadPresentationFile(__version__, lang, _("Please select an Open Document Presentation (.odp) file."))
        
        return uploadPresentationFile(__version__, lang, None)
    
    # TODO: convert the ODP into a slidespeech presentation
    
    # TODO: Do we just want to email the html5 zip file to the given address, or
    # store it locally and provide a link?
#        else:
#
#            # Create time stamped temp directory
#            publishedTime = self.timestamp()
#            tempDir = os.getcwd()+os.sep+"static"+os.sep+publishedTime+os.sep
#            os.makedirs(tempDir)
#
#            # Save ODP into new directory
#            tempFile = tempDir+"temp"+ODPFileExtension
#            savedODP = open(tempFile,"wb")
#            while True:
#                data = myFile.file.read(8192)
#                if not data:
#                    break
#                savedODP.write(data)
#            savedODP.close()
#
#            # Process ODP into PNG files and a script.txt file
#            text = self.processODP(tempFile, tempDir, title, author)
#
#            # Sequence the script and post records to SQL database
#            seq = scriptParser.parseText(text)
#            shutil.copyfile("output.json",tempDir+"output.json")
##            for i, question in enumerate(seq.sequence):
##                shutil.copyfile("sample.png",tempDir+"Slide"+str(i)+".png")
#                    
#            outputFile = ZipFile(tempDir+"output.zip",'w')
#            savePath = os.getcwd()
#            os.chdir(tempDir)
#            tempPathDirectoryList = os.listdir('.')
#            for fileName in tempPathDirectoryList:
#                fileNameStem, fileExtension = os.path.splitext(fileName)
#                if fileExtension in (".png") or fileName=="output.json":
#                    outputFile.write(fileName)
#            outputFile.close()
#            os.chdir(savePath)
#
#            connection = sqlite3.connect('slides.db')
#            cursor = connection.cursor()
#            slideList = []
#            for question in seq.sequence:
#                staticAt = tempDir.find('static')
#                if 0<len(question.linkToShow):
#                    slideList.append([tempDir[staticAt:]+question.linkToShow,
#                                 question.unparsedQuestion])
#                else:
#                    slideList.append(["",
#                                 question.unparsedQuestion])
#
#            #Replace records (if any) with renumbered slides
#            cursor.execute('DELETE FROM slides WHERE tag=?', (ODPFileStem,))
#            for i in range(0,len(slideList)):
#                cursor.execute('INSERT INTO slides VALUES (?,?,?,?,?)',
#                              (ODPFileStem,email,i,slideList[i][0],slideList[i][1]))
#            connection.commit()
#            self.publishSlidesToHtml(tag=ODPFileStem, email=email,publishedTime=publishedTime)
#            scriptList = [(ODPFileStem,email,publishedTime)]
#            return forms.listScripts(__version__,
#                                     "Presentation published. Check e-mail.",
#                                     scriptList,
#                                     ODPFileStem,
#                                     publishedTime,
#                                     email)
#
##            return forms.scriptInputFormWithMessage(__version__,
##                                                    "",
##                                                    ODPFileStem,
##                                                    slideList,
##                                                    "",
##                                                    False,
##                                                    "",
##                                                    email)
    uploadODP.exposed = True

if __name__ == '__main__':
    # CherryPy always starts with app.root when trying to map request URIs
    # to objects, so we need to mount a request handler root. A request
    # to '/' will be mapped to HelloWorld().index().
    cherrypy.config.update({'server.socket_host': '127.0.0.1',
                        'server.socket_port': 10080,
                        'server.thread_pool': 10,
                       })
    config = {'/': {'tools.staticdir.root': os.path.abspath(os.curdir)},
              '/static':{'tools.staticdir.on':True,
                         'tools.staticdir.dir':"static"}}
    cherrypy.quickstart(UploadPage(), config=config)
    
    
    

